<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxePagerEvents } from 'vxe-table'

import { useGetLogPage } from '@fl/api/man-api'
import { useGetMallLogPage } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import { downloadFileWithUrl, multipleFileJsonObj } from '@fl/utils/fn'
import { cloneDeep } from 'lodash-es'

import { blackListColumns, tableTypeEnum } from './constant'

const { meta: { isAdmin } } = useRoute()

const id = defineModel<string | undefined>('id')

const type = defineModel<any>('type')

const buyerId = defineModel<any>('buyerId')

const visible = defineModel<boolean>('visible', { required: true })

const showVisible = ref(false)

const inAndOutTabs = [
    {
        label: '入库',
        name: '0',
    },
    {
        label: '出库',
        name: '1',
    },
]

const blackListTabs = [
    {
        label: '新增',
        name: '2',
    },
    {
        label: '移出',
        name: '3',
    },
]

const tabsList = computed(() => {
    if (type.value === tableTypeEnum.blackList) {
        return blackListTabs
    }
    return inAndOutTabs
})

const activeName = ref(type.value === tableTypeEnum.blackList ? '2' : '0')

const initialState = {
    name: '',
    time: [],
}

const state = ref(cloneDeep(initialState))

const initialShowState = {}

const showState = ref<any>(cloneDeep(initialShowState))

const gridOptions = computed(() => {
    if (type.value === tableTypeEnum.blackList) {
        return {
            columns: blackListColumns,
            rowConfig: {
                keyField: 'id',
            },
            showOverflow: true,
        }
    }
    return {
        columns: [
            { title: '序号', type: 'seq', width: 50 },
            { field: 'supplierName', title: activeName.value === '0' ? '入库供应商' : '出库供应商' },
            { field: 'buyerName', title: '采购商', visible: isAdmin },
            { field: 'remark', title: '说明' },
            { field: 'catName', title: '服务类别' },
            { field: 'createBy', title: '操作人' },
            { field: 'createTime', title: '操作时间' },
            { field: 'file', slots: { default: 'file' }, title: '附件' },
            { slots: { default: 'opreate' }, title: '操作' },
        ],
        rowConfig: {
            keyField: 'id',
        },
        showOverflow: true,
    }
})

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const params = computed(() => {
    return {
        bool: visible.value,
        buyerId: isAdmin ? buyerId.value : '',
        endTime: state.value.time?.[1] || '',
        name: state.value.name,
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
        startTime: state.value.time?.[0] || '',
        type: activeName.value,
    }
})

const { data, isLoading } = isAdmin ? useGetLogPage(params) : useGetMallLogPage(params)

const form = ref()

const tableDate = computed(() => data.value?.records ?? [])

function cancel() {
    visible.value = false
}

function reset() {
    id.value = undefined
}

const columns: PlusColumn[] = [
    {
        label: '供应商名称',
        prop: 'name',
    },
    {
        colProps: {
            span: 10,
        },
        fieldProps: {
            type: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },
        label: '时间范围',
        prop: 'time',
        valueType: 'date-picker',
    },
]

const showColumns: PlusColumn[] = [
    {
        label: '入库供应商',
        prop: 'supplierName',
        valueType: 'text',
    },
    {
        hideInForm: !isAdmin,
        label: '采购商',
        prop: 'buyerName',
        valueType: 'text',
    },
    {
        label: '说明',
        prop: 'remark',
        valueType: 'text',
    },
    {

        label: '服务类别',
        prop: 'catName',
        valueType: 'text',
    },
    {
        label: '操作人',
        prop: 'createBy',
        valueType: 'text',
    },
    {
        label: '操作时间',
        prop: 'createTime',
        valueType: 'text',
    },
    {
        label: '附件',
        prop: 'file',
    },
]

// const

function formReset() {
    tablePage.value = cloneDeep(initialPage)
    state.value = cloneDeep(initialState)
}

function submit(value: any) {
    tablePage.value.currentPage = 1
    state.value = cloneDeep(value)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function formatFile(row: any) {
    if (row.file) {
        return multipleFileJsonObj(row.file)
    }
    return []
}

function showDetail(row: any) {
    showVisible.value = true
    showState.value = row
    console.log(row)
}

function cancelShow() {
    showVisible.value = false
}

function resetShow() {
    showState.value = initialShowState
}

function handleClick() {
    form.value?.formInstance.handleReset()
}

watchEffect(() => {
    if (data.value) {
        tablePage.value.total = data.value?.total ?? 0
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="type"
                width="1200"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <el-tabs v-model="activeName"
                 @tab-click="handleClick"
        >
            <el-tab-pane v-for="item in tabsList"
                         :key="item.name"
                         :label="item.label"
                         :name="item.name"
            />
        </el-tabs>

        <SearchForm v-bind="state"
                    ref="form"
                    submit-text="搜索"
                    :columns="columns"
                    @reset="formReset"
                    @submit="submit"
        />

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="tableDate"
                     @page-change="handlePageChange"
        >
            <template #file="{ row }">
                <div class="truncate flex flex-col">
                    <el-button v-for="item, index in [formatFile(row)?.[0]]"
                               :key="index"
                               text
                               :title="item?.name"
                               @click="downloadFileWithUrl(item?.url, item?.name)"
                    >
                        {{ item?.name }}
                    </el-button>
                </div>
            </template>

            <template #opreate="{ row }">
                <el-button text
                           @click="showDetail(row)"
                >
                    查看
                </el-button>
            </template>
        </SearchTable>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    关闭
                </el-button>
            </div>
        </template>
    </PlusDialog>

    <PlusDialog v-model="showVisible"
                title="详情"
                width="600"
                :has-footer="false"
                close-on-press-escape
                @cancel="cancelShow"
                @closed="resetShow"
    >
        <div class="max-h-600 overflow-auto">
            <PlusForm v-model="showState"
                      :columns="showColumns"
                      :label-width="140"
                      :has-footer="false"
            >
                <template #plus-field-file>
                    <div class="truncate flex flex-col">
                        <el-button v-for="item, index in formatFile(showState)"
                                   :key="index"
                                   text
                                   :title="item?.name"
                                   @click="downloadFileWithUrl(item?.url, item?.name)"
                        >
                            {{ item?.name }}
                        </el-button>
                    </div>
                </template>
            </PlusForm>
        </div>
    </PlusDialog>
</template>
